package cn.com.yang.server.jetty;

import java.io.File;
import java.net.InetAddress;

import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.JettyWebXmlConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;


/**
 * 简单jetty服务器
 * TODO
 * @author yangyijin
 * @since 2024年1月13日-下午3:29:11
 */
public class JettyServer {
	public static void main(String[] args) {
		start(8090);
	}

	/**
	 * 启动jetty
	 * @param port 端口
	 */
	private static void start(int port) {
		QueuedThreadPool pool = new QueuedThreadPool();
		pool.setName("my-jetty-server"/*线程池名字*/);
		pool.setMaxThreads(100/*最大线程数*/);
		pool.setMinThreads(20/*最小线程数*/);
		pool.setIdleTimeout(60000/*空闲时间 ms*/);
		
		Server server = new Server(pool);
		
		Configuration.ClassList.setServerDefault(server)
			.addBefore(JettyWebXmlConfiguration.class.getName(), new String[] {AnnotationConfiguration.class.getName()});
		
		HandlerCollection handlers = new HandlerCollection();
		ContextHandlerCollection contexts = new ContextHandlerCollection();
		handlers.setHandlers(new Handler[] {(Handler)contexts,(Handler)new DefaultHandler()});
		server.setHandler(handlers);
		
		ServerConnector connector = new ServerConnector(server);
		connector.setPort(port);
		server.setConnectors(new Connector[] {connector});
		
		String resources = "webapp";
		String contextPath = "/";
		String resourceBase="";
		WebAppContext ctx = new WebAppContext();
		ctx.setDescriptor(resources+"/WEB-INF/web.xml");
		if(StringUtil.isEmpty(resourceBase)) {
			resourceBase = resources;
		}
		ctx.setResourceBase(resourceBase);
		ctx.setContextPath(contextPath);
		/**
	     * @param java2compliant True if the classloader should delegate first to the parent
	     * classloader (standard java behaviour) or false if the classloader
	     * should first try to load from WEB-INF/lib or WEB-INF/classes (servlet
	     * spec recommendation).  Default is false or can be set by the system
	     * property org.eclipse.jetty.server.webapp.parentLoaderPriority
	     */
		ctx.setParentLoaderPriority(true);
		ctx.setTempDirectory(new File("/temp"));//windows 和linux 不一样
		
		server.setHandler(ctx);
		try {
			server.start();
			String address = InetAddress.getLocalHost().getHostAddress();
			System.out.println("jettyserver启动成功 sucess "+port +" "+address);
		} catch (Exception e) {
			System.out.println("jettyserver启动失败："+e);
		}
	}
}